<template>
    <div class="ios-requests-page">
        <div class="ios-container">
            <div class="ios-row">
                <!-- 左侧筛选栏 - 苹果风格 -->
                <div class="ios-sidebar">
                    <div class="ios-panel">
                        <div class="panel-header">
                            <h3>筛选条件</h3>
                        </div>
                        <div class="ios-filter-list">
                            <div class="filter-section">
                                <h4>预算区间</h4>
                                <div class="budget-range-display">
                                    <div class="price-label">¥{{ budgetRange[0] }}</div>
                                    <div class="price-separator">至</div>
                                    <div class="price-label">¥{{ budgetRange[1] }}</div>
                                </div>
                                <el-slider
                                    v-model="budgetRange"
                                    range
                                    :min="0"
                                    :max="10000"
                                    :step="100"
                                    :format-tooltip="formatPrice"
                                />
                                <div class="price-range-text">
                                    当前筛选价格范围：¥{{ budgetRange[0] }} - ¥{{ budgetRange[1] }}
                                </div>
                            </div>
                            
                            <div class="filter-section">
                                <h4>求购类型</h4>
                                <div class="category-grid">
                                    <div 
                                        v-for="category in categories" 
                                        :key="category.id"
                                        :class="['category-item', { active: categoryFilter.includes(category.name) }]"
                                        @click="toggleCategoryFilter(category.name)"
                                    >
                                        <div class="category-icon-wrapper">
                                            <template v-if="category.icon">
                                                <img 
                                                    v-if="typeof category.icon === 'string' && category.icon.startsWith('http')"
                                                    :src="category.icon" 
                                                    :alt="category.name + ' icon'" 
                                                    class="category-icon"
                                                />
                                                <component 
                                                    v-else 
                                                    :is="getCategoryIconComponent(category.icon)" 
                                                    class="category-icon-component" 
                                                />
                                            </template>
                                            <component 
                                                v-else 
                                                :is="getCategoryIconComponent(category.name.toLowerCase())" 
                                                class="category-icon-component" 
                                            />
                                        </div>
                                        <div class="category-name">{{ category.name }}</div>
                                    </div>
                                </div>
                            </div>
                            

                            
                            <div class="filter-buttons">
                                <el-button @click="resetFilters" plain>重置</el-button>
                                <el-button type="primary" @click="applyFilters">应用</el-button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 右侧内容区 -->
                <div class="ios-main-content">
                    <!-- 合并页面顶部元素到一行 -->
                    <div class="ios-content-header">
                        <h2>用户求购信息</h2>
                        <div class="header-actions">
                            <span class="result-count">共 {{ filteredRequests.length }} 条求购信息</span>
                            
                            <div class="filter-button-wrapper">
                            <el-dropdown @command="handleSort" trigger="click">
                                    <div class="filter-button">
                                    <span>{{ getSortLabel() }}</span>
                                    <el-icon><ArrowDown /></el-icon>
                                </div>
                                <template #dropdown>
                                    <el-dropdown-menu>
                                        <el-dropdown-item command="newest">最新发布</el-dropdown-item>
                                        <el-dropdown-item command="priceAsc">预算从低到高</el-dropdown-item>
                                        <el-dropdown-item command="priceDesc">预算从高到低</el-dropdown-item>
                                        <el-dropdown-item command="mostViewed">最多浏览</el-dropdown-item>
                                    </el-dropdown-menu>
                                </template>
                            </el-dropdown>
                            </div>
                            
                            <div class="school-select-wrapper">
                                <el-dropdown @command="handleSchoolSelect" trigger="click">
                                    <div class="school-select-button">
                                        <span>{{ schoolFilter || '选择学校' }}</span>
                                        <el-icon><ArrowDown /></el-icon>
                                    </div>
                                    <template #dropdown>
                                        <el-dropdown-menu>
                                            <el-dropdown-item command="">全部学校</el-dropdown-item>
                                            <el-dropdown-item 
                                                v-for="school in schoolOptions" 
                                                :key="school.value" 
                                                :command="school.value"
                                            >
                                                {{ school.label }}
                                            </el-dropdown-item>
                                        </el-dropdown-menu>
                                    </template>
                                </el-dropdown>
                            </div>
                            

                        </div>
                    </div>
                    
                    <!-- 初始加载状态 -->
                    <div v-if="isLoading && requests.length === 0" class="initial-loading-container">
                        <div class="loading-spinner">
                            <svg viewBox="0 0 50 50" class="spinner">
                                <circle class="path" cx="25" cy="25" r="20" fill="none" stroke-width="4"></circle>
                            </svg>
                        </div>
                        <div class="loading-text-container">
                            <p class="loading-title">正在获取求购信息</p>
                            <p class="loading-subtitle">{{ isUsingMockData ? '加载本地数据中...' : '从服务器获取最新数据中...' }}</p>
                        </div>
                    </div>

                    <!-- 筛选结果为空 -->
                    <div v-else-if="!isLoading && filteredRequests.length === 0" class="empty-result">
                        <el-empty description="暂无符合条件的求购信息">
                            <template #description>
                                <p>暂无符合条件的求购信息</p>
                                <p class="empty-hint">{{ isUsingMockData ? '当前使用的是本地模拟数据，请尝试调整筛选条件' : '请尝试调整筛选条件或稍后再试' }}</p>
                            </template>
                        </el-empty>
                    </div>

                    <!-- 求购列表卡片 -->
                    <div v-else class="ios-requests-grid">
                        <div 
                            v-for="request in filteredRequests" 
                            :key="request.id"
                            class="ios-request-card"
                        >
                            <div class="request-header">
                                <div class="user-info">
                                    <el-avatar :size="40" :src="request.user.avatar && !request.user.avatar.startsWith('http') && !request.user.avatar.startsWith('/src/assets/') ? '/images/user/' + request.user.avatar : request.user.avatar || '/src/assets/avatar.png'"></el-avatar>
                                    <div class="user-details">
                                        <div class="user-name">{{ request.user.name }}</div>
                                        <div class="user-school">{{ request.user.school }}</div>
                                    </div>
                                </div>
                                <div class="request-actions-top">
                                <div class="request-time">{{ request.time }}</div>
                                    <el-button 
                                        type="text" 
                                        class="favorite-button" 
                                        @click.stop="toggleFavorite(request)"
                                        :class="{ 'is-favorite': request.isFavorite }"
                                    >
                                        <el-icon><Star /></el-icon>
                                    </el-button>
                                </div>
                            </div>
                            <div class="request-body">
                                <h3 class="request-title">{{ request.title }}</h3>
                                <p class="request-content">{{ request.content }}</p>
                                <div class="request-tags">
                                    <el-tag size="small" v-if="request.category">
                                        <span class="tag-with-icon">
                                            <template v-if="getCategoryIcon(request.category)">
                                                <img 
                                                    v-if="typeof getCategoryIcon(request.category) === 'string' && getCategoryIcon(request.category).startsWith('http')"
                                                    :src="getCategoryIcon(request.category)" 
                                                    :alt="request.category + ' icon'" 
                                                    class="tag-icon-img"
                                                />
                                                <component 
                                                    v-else 
                                                    :is="getCategoryIconComponent(getCategoryIcon(request.category))" 
                                                    class="tag-icon-component" 
                                                />
                                            </template>
                                            <component 
                                                v-else 
                                                :is="getCategoryIconComponent(request.category.toLowerCase())" 
                                                class="tag-icon-component" 
                                            />
                                            {{ request.category }}
                                        </span>
                                    </el-tag>
                                    <el-tag size="small" type="info" v-if="request.condition">{{ request.condition }}</el-tag>
                                </div>
                            </div>
                            <div class="request-footer">
                                <div class="request-budget">预算: ¥{{ request.budget }}</div>
                                <div class="request-actions">
                                    <el-button type="primary" size="small" @click="contactUser(request)">联系</el-button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- 没有结果时的提示 -->
                    <div v-if="filteredRequests.length === 0 && !isLoading" class="empty-result">
                        <el-empty description="暂无符合条件的求购信息" />
                    </div>

                    <!-- 加载更多 -->
                    <div v-if="filteredRequests.length > 0" class="loading-more-container">
                        <div v-if="isLoading" class="loading-indicator">
                            <span class="loading-dot"></span>
                            <span class="loading-dot"></span>
                            <span class="loading-dot"></span>
                            <span class="loading-text">{{ isUsingMockData ? '正在加载本地数据...' : '正在获取更多求购信息...' }}</span>
                        </div>
                        <div v-else-if="isAllLoaded" class="all-loaded-text">
                            <span>— 已经到底啦，没有更多求购信息了 —</span>
                        </div>
                        <div v-else class="load-more-hint">
                            <span>— 下拉加载更多 —</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 发布求购对话框 -->
        <el-dialog
            v-model="showPublishDialog"
            title="发布求购"
            width="40%"
            :destroy-on-close="true"
            class="apple-style-dialog"
        >
            <el-form :model="newRequest" label-position="left" label-width="120px">
                <el-row :gutter="20">
                    <el-col :span="24">
                <el-form-item label="求购标题">
                            <el-input v-model="newRequest.title" placeholder="请输入求购标题" class="apple-style-input" style="width: 100%;" />
                </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="求购内容" prop="content">
                    <el-input 
                        v-model="newRequest.content" 
                        type="textarea" 
                        rows="5"
                        placeholder="详细描述您需要的物品、参数要求等" 
                        class="apple-style-textarea"
                    />
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="24">
                <el-form-item label="求购分类">
                            <el-select v-model="newRequest.category" placeholder="选择分类" class="apple-style-select" style="width: 100%;">
                        <el-option 
                            v-for="category in categories" 
                            :key="category.id" 
                            :label="category.name" 
                            :value="category.name" 
                        >
                            <div class="category-option">
                                <template v-if="category.icon">
                                    <img 
                                        v-if="typeof category.icon === 'string' && category.icon.startsWith('http')"
                                        :src="category.icon" 
                                        :alt="category.name + ' icon'" 
                                        class="category-icon-img"
                                    />
                                    <component 
                                        v-else 
                                        :is="getCategoryIconComponent(category.icon)" 
                                        class="category-icon-component" 
                                    />
                                </template>
                                <component 
                                    v-else 
                                    :is="getCategoryIconComponent(category.name.toLowerCase())" 
                                    class="category-icon-component" 
                                />
                                <span>{{ category.name }}</span>
                            </div>
                        </el-option>
                    </el-select>
                </el-form-item>
                    </el-col>
                </el-row>
                    
                <el-row :gutter="20">
                    <el-col :span="12">
                <el-form-item label="预算">
                            <el-input-number v-model="newRequest.budget" :min="0" :step="10" :precision="0" class="apple-style-input-number" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="过期时间" prop="expireTime">
                            <el-date-picker
                                v-model="newRequest.expireTime"
                                type="datetime"
                                placeholder="选择过期时间"
                                style="width: 100%;"
                                class="apple-style-select"
                                format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss"
                            />
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="联系信息" prop="contactInfo">
                    <el-input v-model="newRequest.contactInfo" placeholder="请输入您的联系方式 (如QQ, 微信, 电话)" class="apple-style-input" style="width: 100%;" />
                </el-form-item>

                <el-form-item label="交易位置">
                    <div class="location-input-container">
                        <el-input 
                            v-model="newRequest.location" 
                            placeholder="已自动填充学校名称，请继续输入详细位置" 
                            class="apple-style-input modern-input location-field"
                        />
                    </div>
                    <div class="form-item-tips">学校名称已自动填充，请继续输入具体位置如教学楼、宿舍等</div>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button class="apple-style-btn cancel-btn" @click="showPublishDialog = false">取消</el-button>
                    <el-button class="apple-style-btn confirm-btn" type="primary" @click="submitRequest">发布</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 调试面板 -->
        <el-dialog
            v-model="showDebugPanel"
            title="调试信息"
            width="500px"
            class="ios-dialog"
        >
            <div class="debug-content">
                <div class="debug-item">
                    <span class="label">API URL:</span>
                    <span class="value">{{ debugInfo.apiUrl }}</span>
                </div>
                <div class="debug-item">
                    <span class="label">响应状态:</span>
                    <span class="value">{{ debugInfo.responseStatus }}</span>
                </div>
                <div class="debug-item">
                    <span class="label">原始数据:</span>
                    <span class="value">{{ debugInfo.rawData ? JSON.stringify(debugInfo.rawData).substring(0, 100) + '...' : '无' }}</span>
                </div>
                <div class="debug-item">
                    <span class="label">解析后的数据项:</span>
                    <span class="value">{{ debugInfo.parsedItems.length }} 项</span>
                </div>
                <div class="debug-item">
                    <span class="label">格式化后的数据项:</span>
                    <span class="value">{{ debugInfo.formattedItems.length }} 项</span>
                </div>
                <div class="debug-item">
                    <span class="label">错误信息:</span>
                    <span class="value">{{ debugInfo.errorMessages.join('\n') }}</span>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showDebugPanel = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, reactive, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { Search, ArrowDown, Plus, Share, Star } from '@element-plus/icons-vue';
import { ElMessage, ElNotification } from 'element-plus';
import { favoriteRequest, unfavoriteRequest } from '@/api/request';
// 导入图标组件
import { 
    Cellphone, 
    Monitor, 
    Reading, 
    HomeFilled, 
    ShoppingBag, 
    GoodsFilled, 
    Basketball, 
    Bicycle,
    Cpu, 
    Document, 
    Collection, 
    Bowl, 
    Handbag, 
    Trophy, 
    Watch, 
    ChatDotRound, 
    Tickets, 
    Menu,
    Opportunity,
    Notebook,
    Football,
    Suitcase,
    Briefcase,
    PhoneFilled,
    Location,
    ArrowRightBold,
    Minus,
    Calendar,
    Money,
    ChatLineSquare,
    View
} from '@element-plus/icons-vue';
import { useUserStore } from '@/stores/user';


const router = useRouter();
const userStore = useUserStore();


const loading = ref(true);
const sortBy = ref('newest');
const dialogVisible = ref(false);
const requestForm = reactive({
    title: '',
    categoryId: '',
    price: '',
    description: '',
    contactInfo: '',
    expirationTime: '',
    tradeLocation: '',
});
const isEdit = ref(false);
const currentEditId = ref(null);
const searchQuery = ref('');
// 添加学校筛选相关数据
const schoolFilter = ref('');


// 定义图标映射
const categoryIcons = {
    // 电子产品相关
    'electronics': Monitor,
    'phone': PhoneFilled,
    'computer': Monitor,
    'smart': Watch,
    'hardware': Cpu,
    
    // 书籍教材相关
    'book': Reading,
    'document': Document,
    'exam': Collection,
    'novel': Notebook,
    
    // 生活用品相关
    'daily': HomeFilled,
    'life': HomeFilled,
    'kitchen': Bowl,
    
    // 服装相关
    'clothes': GoodsFilled,
    'cloth': GoodsFilled,
    'female': Handbag,
    'bag': Briefcase,
    
    // 运动相关
    'sports': Basketball,
    'sport': Basketball,
    'fitness': Trophy,
    'bike': Bicycle,
    'ball': Football,
    
    // 票券小物
    'tickets': Tickets,
    'opportunity': Opportunity,
    
    // 其他类型
    'other': Menu,
    'shopping': ShoppingBag,
    'case': Suitcase
};

// 获取分类图标组件
const getCategoryIconComponent = (iconName) => {
    try {
        if (!iconName) return categoryIcons['other'];
        
        // 如果直接匹配到了完整名称
        if (categoryIcons[iconName]) {
            return categoryIcons[iconName];
        }
        
        // 尝试匹配部分名称
        for (const key in categoryIcons) {
            if (iconName.toLowerCase().includes(key) || key.includes(iconName.toLowerCase())) {
                return categoryIcons[key];
            }
        }
        
        // 没有匹配到，返回默认图标
        return categoryIcons['other'];
    } catch (error) {
        console.error('获取图标组件失败:', error);
        return categoryIcons['other'];
    }
};

// 根据分类名称获取图标
const getCategoryIcon = (categoryName) => {
    try {
        if (!categoryName) return null;
        
        // 查找精确匹配的分类
        const category = categories.value.find(cat => cat.name === categoryName);
        if (category && category.icon) {
            return category.icon;
        }
        
        // 如果没有找到精确匹配，尝试部分匹配
        for (const cat of categories.value) {
            if (cat.name.includes(categoryName) || categoryName.includes(cat.name)) {
                if (cat.icon) return cat.icon;
            }
        }
        
        // 如果仍未找到，返回null，让调用者决定如何处理
        return null;
    } catch (error) {
        console.error('获取分类图标失败:', error);
        return null;
    }
};

// API基础URL
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080/api';

// 搜索和筛选状态
const searchKeyword = ref('');
const sortOption = ref('newest');
const pageSize = ref(12);
const total = ref(0);
const budgetRange = ref([0, 5000]);
const categoryFilter = ref([]);
const showPublishDialog = ref(false);
const isLoading = ref(false);
const isAllLoaded = ref(false);
const page = ref(1);
const isUsingMockData = ref(false);  // 标记是否使用模拟数据
const categories = ref([]); // 存储从API获取的分类列表

// 新求购信息
const newRequest = ref({
    title: '',
    content: '',
    category: '',
    condition: '不限',
    budget: 0,
    schoolId: '',
    location: '',
    contactInfo: '',
    expireTime: null
});

// 学校选项
const schoolOptions = [
    { value: '北京大学', label: '北京大学' },
    { value: '清华大学', label: '清华大学' },
    { value: '中国人民大学', label: '中国人民大学' },
    { value: '北京师范大学', label: '北京师范大学' },
    { value: '浙江大学', label: '浙江大学' },
    { value: '复旦大学', label: '复旦大学' }
];

// 获取商品分类列表
const fetchCategories = async () => {
    try {
        // 通过API获取分类信息
        const response = await fetch(`${API_BASE_URL}/products/categories`);
        if (!response.ok) {
            throw new Error(`获取分类失败: ${response.status}`);
        }
        
        const data = await response.json();
        if (data.code === 200 && data.data) {
            categories.value = data.data;
            console.log('成功获取分类列表:', categories.value);
        } else {
            console.error('获取分类失败:', data.message || '未知错误');
            // 使用模拟分类数据作为备用
            categories.value = mockCategories;
            isUsingMockData.value = true;
        }
    } catch (error) {
        console.error('获取分类失败:', error);
        // 使用模拟分类数据作为备用
        categories.value = mockCategories;
        isUsingMockData.value = true;
    }
};

// 模拟分类数据（备用）
const mockCategories = [
    { id: 1, name: '电子产品', icon: 'electronics' },
    { id: 7, name: '手机数码', icon: 'electronics', parentId: 1 },
    { id: 8, name: '电脑配件', icon: 'electronics', parentId: 1 },
    { id: 2, name: '图书教材', icon: 'book' },
    { id: 9, name: '课本教材', icon: 'book', parentId: 2 },
    { id: 10, name: '考试资料', icon: 'book', parentId: 2 },
    { id: 3, name: '生活用品', icon: 'daily' },
    { id: 4, name: '服装鞋帽', icon: 'clothes' },
    { id: 5, name: '运动健身', icon: 'sports' },
    { id: 11, name: '球类装备', icon: 'sports', parentId: 5 },
    { id: 12, name: '健身器材', icon: 'sports', parentId: 5 },
    { id: 13, name: '厨房用品', icon: 'daily', parentId: 3 },
    { id: 14, name: '宿舍用品', icon: 'daily', parentId: 3 },
    { id: 15, name: '男装', icon: 'clothes', parentId: 4 },
    { id: 16, name: '女装', icon: 'clothes', parentId: 4 },
    { id: 17, name: '智能设备', icon: 'electronics', parentId: 1 },
    { id: 18, name: '小说文学', icon: 'book', parentId: 2 },
    { id: 6, name: '票券小物', icon: 'other' }
];

// 实际使用的求购数据
const requests = ref([]);

// 添加一个ref用于保存原始响应数据供调试
const rawResponseData = ref(null);
const showDebugPanel = ref(false);
const debugInfo = ref({
  apiUrl: '',
  responseStatus: '',
  rawData: null,
  parsedItems: [],
  formattedItems: [],
  errorMessages: []
});

// 添加一个辅助函数，将分类ID转换为分类名称
const getCategoryNameById = (categoryId) => {
    if (!categoryId) return '未分类';
    const category = categories.value.find(cat => cat.id === categoryId);
    return category ? category.name : '未知分类';
};

// 从后端获取求购数据
const fetchWantedData = async () => {
    isLoading.value = true;
    debugInfo.value.errorMessages = [];
    console.log('开始获取求购数据...');
    
    try {
        // 构建请求参数（仅保留分页和排序参数，筛选由前端完成）
        const params = new URLSearchParams();
        if (page.value) params.append('page', page.value.toString());
        if (pageSize.value) params.append('pageSize', pageSize.value.toString());
        
        // 排序参数保留，因为排序最好在数据库层面完成
        params.append('sortBy', sortOption.value);
        
        // 添加用户ID，从localStorage获取
        const userInfo = localStorage.getItem('userInfo');
        const token = localStorage.getItem('token');
        let userId = null;
        
        if (userInfo) {
            try {
                const parsedUserInfo = JSON.parse(userInfo);
                if (parsedUserInfo.id) {
                    userId = parsedUserInfo.id;
                    params.append('userId', userId.toString());
                    console.log('添加用户ID到请求:', userId);
                }
            } catch (e) {
                console.error('解析用户信息失败:', e);
            }
        }
        
        // 为调试目的记录完整URL
        const apiUrl = `${API_BASE_URL}/requests?${params.toString()}`;
        debugInfo.value.apiUrl = apiUrl;
        console.log('正在请求求购数据，URL:', apiUrl);
        
        // 准备请求头
        const headers = {
            'Content-Type': 'application/json'
        };
        
        // 如果有token，添加到请求头
        if (token) {
            headers['Authorization'] = `Bearer ${token}`;
        }
        
        // 发起API请求
        const response = await fetch(apiUrl, {
            method: 'GET',
            headers: headers
        });
        
        // 记录响应状态
        debugInfo.value.responseStatus = `${response.status} ${response.statusText}`;
        console.log('响应状态:', response.status, response.statusText);
        
        // 检查响应状态
        if (!response.ok) {
            throw new Error(`API请求失败: ${response.status} ${response.statusText}`);
        }
        
        // 获取原始响应文本用于调试
        const responseText = await response.text();
        console.log('原始响应文本:', responseText);
        
        // 解析为JSON (安全解析)
        let data;
        try {
            data = responseText ? JSON.parse(responseText) : null;
            rawResponseData.value = data; // 保存原始响应
            debugInfo.value.rawData = data;
            console.log('解析为JSON:', data);
        } catch (parseError) {
            debugInfo.value.errorMessages.push(`JSON解析错误: ${parseError.message}`);
            console.error('JSON解析错误:', parseError);
            throw new Error(`响应不是有效的JSON: ${parseError.message}`);
        }
        
        if (!data) {
            debugInfo.value.errorMessages.push('响应为空或无效');
            throw new Error('响应数据为空或无效');
        }
        
        // 处理所有可能的数据结构路径
        let wantedItems = [];
        let totalItems = 0;
        
        // 尝试所有可能的数据结构路径
        if (data.code === 200 && data.data) {
            // 标准API响应 {code: 200, message: "...", data: {...}}
            if (Array.isArray(data.data.items)) {
                // {code: 200, data: {items: [...], total: x}}
                wantedItems = data.data.items;
                totalItems = data.data.total || wantedItems.length;
                debugInfo.value.errorMessages.push('使用路径: data.data.items');
            } else if (Array.isArray(data.data.content)) {
                // {code: 200, data: {content: [...], total: x}} - 分页格式
                wantedItems = data.data.content;
                totalItems = data.data.totalElements || data.data.total || wantedItems.length;
                debugInfo.value.errorMessages.push('使用路径: data.data.content');
            } else if (Array.isArray(data.data)) {
                // {code: 200, data: [...]}
                wantedItems = data.data;
                totalItems = wantedItems.length;
                debugInfo.value.errorMessages.push('使用路径: data.data (数组)');
            } else {
                // 单条数据 {code: 200, data: {id: 1, ...}}
                if (data.data.id) {
                    wantedItems = [data.data];
                    totalItems = 1;
                    debugInfo.value.errorMessages.push('使用路径: data.data (单条数据)');
                }
            }
        } else if (Array.isArray(data.items)) {
            // {items: [...], total: x}
            wantedItems = data.items;
            totalItems = data.total || wantedItems.length;
            debugInfo.value.errorMessages.push('使用路径: data.items');
        } else if (Array.isArray(data)) {
            // 直接数组 [...]
            wantedItems = data;
            totalItems = wantedItems.length;
            debugInfo.value.errorMessages.push('使用路径: 直接数组');
        } else if (data.id) {
            // 单条数据 {id: 1, ...}
            wantedItems = [data];
            totalItems = 1;
            debugInfo.value.errorMessages.push('使用路径: 直接对象(单条)');
        } else if (data.results && Array.isArray(data.results)) {
            // {results: [...], count: x}
            wantedItems = data.results;
            totalItems = data.count || wantedItems.length;
            debugInfo.value.errorMessages.push('使用路径: data.results');
        } else {
            // 如果都不是，尝试提取数据中任何看起来像数组的字段
            for (const key in data) {
                if (Array.isArray(data[key])) {
                    wantedItems = data[key];
                    totalItems = wantedItems.length;
                    debugInfo.value.errorMessages.push(`使用路径: data.${key} (推测数组)`);
                    break;
                }
            }
        }
        
        // 记录找到的数据
        debugInfo.value.parsedItems = wantedItems;
        console.log('找到的数据项:', wantedItems.length, '条记录', wantedItems);
        
        // 如果没有找到任何项目但数据不为空，尝试调试这个数据
        if (wantedItems.length === 0 && data) {
            console.warn('没有从数据中找到项目数组:', data);
            debugInfo.value.errorMessages.push('未找到有效的数据数组结构');
            // 尝试打印出所有可能的路径
            const paths = findAllArrayPaths(data);
            console.log('可能的数据数组路径:', paths);
            debugInfo.value.errorMessages.push(`可能的数组路径: ${paths.join(', ')}`);
            
            // 创建一个合成数据用于显示原始数据结构
            wantedItems = [{
                id: 1,
                title: '调试项 - 未能解析数据结构',
                description: `请查看控制台以获取更多信息 - ${JSON.stringify(data).substring(0, 100)}...`,
                createdAt: new Date(),
                user: { username: '系统' }
            }];
            totalItems = 1;
        }
        
        // 更新总数
        total.value = totalItems;
        
        // 确保有数据才处理
        if (wantedItems && wantedItems.length > 0) {
            // 格式化后端数据为前端所需格式
            const formattedItems = wantedItems.map(item => {
                try {
                    // 安全地访问属性，避免异常
                    const safeItem = {
                        id: getNestedValue(item, 'id') || Math.random().toString(36).substr(2, 9),
                        title: getNestedValue(item, 'title') || getNestedValue(item, 'name') || '未知标题',
                        content: getNestedValue(item, 'description') || getNestedValue(item, 'content') || getNestedValue(item, 'text') || '无描述',
                        budget: parseFloat(getNestedValue(item, 'budget')) || parseFloat(getNestedValue(item, 'price')) || 0,
                        time: getNestedValue(item, 'time') || formatTimeAgo(getNestedValue(item, 'publishTime') || getNestedValue(item, 'createdAt') || getNestedValue(item, 'createTime') || new Date()),
                        category: getNestedValue(item, 'categoryName') || getNestedValue(item, 'category') || (getNestedValue(item, 'categoryId') ? getCategoryNameById(getNestedValue(item, 'categoryId')) : '未分类'),
                        condition: getNestedValue(item, 'condition') || '不限',
                        isFavorite: getNestedValue(item, 'isFavorite') || false,
                        user: {
                            id: getNestedValue(item, 'user.id') || getNestedValue(item, 'userId') || 0,
                            name: getNestedValue(item, 'user.name') || getNestedValue(item, 'user.nickname') || getNestedValue(item, 'user.username') || getNestedValue(item, 'username') || getNestedValue(item, 'userName') || '未知用户',
                            avatar: getNestedValue(item, 'user.avatar') || getNestedValue(item, 'avatar') || '/src/assets/avatar.png',
                            school: getNestedValue(item, 'user.school') || getNestedValue(item, 'school.name') || getNestedValue(item, 'schoolName') || schoolFilter.value || '未知学校'
                        },
                        views: parseInt(getNestedValue(item, 'views')) || parseInt(getNestedValue(item, 'viewCount')) || 0
                    };
                    return safeItem;
                } catch (itemError) {
                    console.error('处理单个求购项时出错:', itemError, item);
                    // 返回一个安全的默认值
                    return {
                        id: Math.random().toString(36).substr(2, 9),
                        title: '数据解析错误',
                        content: `无法解析此项: ${itemError.message}`,
                        budget: 0,
                        time: '未知',
                        category: '错误',
                        condition: '未知',
                        user: {
                            name: '系统',
                            avatar: '/src/assets/avatar.png',
                            school: '未知学校'
                        },
                        views: 0
                    };
                }
            });
            
            debugInfo.value.formattedItems = formattedItems;
            console.log('格式化后的数据:', formattedItems);
            
            if (page.value === 1) {
                console.log('替换原有数据');
                requests.value = formattedItems;
            } else {
                console.log('追加新数据');
                requests.value = [...requests.value, ...formattedItems];
            }
            
            isUsingMockData.value = false;
            console.log('成功获取后端求购数据', formattedItems.length, '条记录, 当前使用模拟数据:', isUsingMockData.value);
        } else {
            console.warn('后端返回的数据为空');
            debugInfo.value.errorMessages.push('后端返回的数据为空');
            throw new Error('无求购数据');
        }
    } catch (error) {
        console.error('获取求购数据失败:', error);
        debugInfo.value.errorMessages.push(`错误: ${error.message}`);
        
        // 如果是第一页请求失败或返回空数据，才使用模拟数据
        if (page.value === 1 && (requests.value.length === 0 || isUsingMockData.value)) {
            requests.value = mockRequests;
            total.value = mockRequests.length;
            isUsingMockData.value = true;
            console.log('使用模拟求购数据，因为:', error.message);
            ElMessage.warning(`获取求购数据失败: ${error.message}，已加载本地模拟数据`);
        } else {
            ElMessage.error(`加载更多数据失败: ${error.message}`);
        }
    } finally {
        isLoading.value = false;
        console.log('数据加载完成，当前数据源:', isUsingMockData.value ? '模拟数据' : '后端数据');
        console.log('当前请求页:', page.value, '总条数:', total.value, '已加载:', requests.value.length);
    }
};

// 安全获取嵌套属性
const getNestedValue = (obj, path) => {
    if (!obj) return undefined;
    const parts = path.split('.');
    let current = obj;
    for (const part of parts) {
        if (current == null || typeof current !== 'object') return undefined;
        current = current[part];
    }
    return current;
};

// 切换调试面板
const toggleDebugPanel = () => {
    showDebugPanel.value = !showDebugPanel.value;
};

// 格式化时间为"几小时前"、"几天前"等形式
const formatTimeAgo = (dateStr) => {
    try {
        const now = new Date();
        const past = new Date(dateStr);
        const diffInSeconds = Math.floor((now - past) / 1000);
        
        if (diffInSeconds < 60) return `${diffInSeconds}秒前`;
        if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`;
        if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`;
        if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)}天前`;
        if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)}个月前`;
        return `${Math.floor(diffInSeconds / 31536000)}年前`;
    } catch (e) {
        console.error('时间格式化错误:', e);
        return '未知时间';
    }
};

// 筛选后的求购数据 - 恢复前端筛选逻辑
const filteredRequests = computed(() => {
    if (!Array.isArray(requests.value)) return [];
    
    return requests.value.filter(item => {
        // 检查是否匹配搜索关键词
        const matchesSearch = searchKeyword.value === '' || 
            item.title.toLowerCase().includes(searchKeyword.value.toLowerCase()) || 
            item.content.toLowerCase().includes(searchKeyword.value.toLowerCase());
        
        // 检查是否匹配类别筛选
        const matchesCategory = categoryFilter.value.length === 0 || 
            categoryFilter.value.includes(item.category);
        
        // 检查是否匹配价格范围
        const matchesBudget = item.budget >= budgetRange.value[0] && 
            item.budget <= budgetRange.value[1];
    
        // 检查是否匹配学校筛选
        const matchesSchool = schoolFilter.value === '' || 
            (item.user.school && item.user.school.includes(schoolFilter.value));
            
        // 检查是否匹配状态筛选
        const matchesStatus = statusFilter.value === '' || 
            (item.status && item.status === statusFilter.value);
        
        return matchesSearch && matchesCategory && matchesBudget && matchesSchool && matchesStatus;
    }).sort((a, b) => {
        // 排序逻辑保持不变
        if (sortOption.value === 'createTime') {
            return new Date(b.createTime) - new Date(a.createTime);
        } else if (sortOption.value === 'priceAsc') {
            return a.price - b.price;
        } else if (sortOption.value === 'priceDesc') {
            return b.price - a.price;
        } else if (sortOption.value === 'viewCount') {
            return b.viewCount - a.viewCount;
    }
        return 0;
    });
});

// 获取排序标签
const getSortLabel = () => {
    switch (sortOption.value) {
        case 'newest': return '最新发布';
        case 'priceAsc': return '预算从低到高';
        case 'priceDesc': return '预算从高到低';
        case 'mostViewed': return '最多浏览';
        default: return '排序方式';
    }
};

// 处理排序选择
const handleSort = (command) => {
    sortOption.value = command;
    page.value = 1;
    fetchWantedData();
};

// 格式化价格
const formatPrice = (val) => {
    return `¥${val}`;
};

// 重置筛选条件
const resetFilters = () => {
    budgetRange.value = [0, 5000];
    categoryFilter.value = [];
    schoolFilter.value = '';
    statusFilter.value = '';
    page.value = 1;
    isAllLoaded.value = false;
};

// 应用筛选
const applyFilters = () => {
    // 仅更新筛选条件，不再发送API请求
    // 由前端通过filteredRequests计算属性完成筛选
    ElMessage.success('筛选条件已应用');
};

// 处理搜索
const handleSearch = () => {
    // 仅更新搜索关键词，不再发送API请求
    // 由前端通过filteredRequests计算属性完成筛选
};

// 加载更多数据
const loadMore = () => {
    if (isLoading.value || isAllLoaded.value) return;
    
        page.value++;
    fetchWantedData();
};

// 滚动监听处理
const handleScroll = () => {
    const mainContent = document.querySelector('.ios-main-content');
    if (!mainContent) return;
    
    const scrollTop = mainContent.scrollTop;
    const scrollHeight = mainContent.scrollHeight;
    const clientHeight = mainContent.clientHeight;
    
    // 当距离底部100px时加载更多
    if (scrollHeight - scrollTop - clientHeight < 100 && !isLoading.value && !isAllLoaded.value) {
        loadMore();
    }
};

// 发布求购
const publishRequest = () => {
    showPublishDialog.value = true;
};

// 提交求购信息
const submitRequest = async () => {
    if (!newRequest.value.title || !newRequest.value.content || !newRequest.value.category) {
        ElMessage.warning('请完善求购信息');
        return;
    }
    
    try {
        // 检查用户是否已登录
        const token = localStorage.getItem('token');
        if (!token) {
            ElMessage.warning('请先登录后再发布求购信息');
            router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
            return;
        }
        
        // 调用API保存求购信息 - 需要从分类名称转换为分类ID
        const categoryObj = categories.value.find(cat => cat.name === newRequest.value.category);
        const categoryId = categoryObj ? categoryObj.id : null;
        
        if (!categoryId) {
            console.warn('无法找到与分类名称匹配的分类ID:', newRequest.value.category);
        }
        
        const requestData = {
            title: newRequest.value.title,
            description: newRequest.value.content,
            budget: newRequest.value.budget,
            categoryId: categoryId,  // 使用分类ID而不是名称
            condition: newRequest.value.condition,
            contactInfo: '用户未提供联系方式', // 默认值
            expireTime: new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000).toISOString() // 30天后过期
        };
        
        const response = await fetch(`${API_BASE_URL}/requests`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify(requestData)
        });
        
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.message || `API请求失败: ${response.status}`);
        }
        
    ElMessage.success('求购信息发布成功');
    showPublishDialog.value = false;
    
    // 重置表单
    newRequest.value = {
        title: '',
        content: '',
        category: '',
        condition: '不限',
            budget: 0,
            schoolId: '',
            location: '',
            contactInfo: '',
            expireTime: null
    };
        
        // 刷新数据
        page.value = 1;
        fetchWantedData();
    } catch (error) {
        console.error('发布求购失败:', error);
        ElMessage.error(error.message || '发布求购失败，请稍后重试');
    }
};

// 联系用户
const contactUser = async (request) => {
    try {
        // 检查用户是否已登录
        const token = localStorage.getItem('token');
        const userInfo = localStorage.getItem('userInfo');
        if (!token || !userInfo) {
            ElMessage.warning('请先登录后再联系求购者');
            router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
            return;
        }
        
        const userId = JSON.parse(userInfo).id;
        if (!userId) {
            ElMessage.warning('无法获取用户信息，请重新登录');
            return;
        }

        if (!request.user || !request.user.id) {
            ElMessage.error('无法获取求购者信息');
            return;
        }
        
        // 发送联系请求
        const response = await fetch(`${API_BASE_URL}/requests/${request.id}/contact`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${token}`
            },
            body: JSON.stringify({
                message: '您好，我看到了您的求购信息，想和您详细聊一下。'
            })
        });
        
        // 获取响应数据
        const data = await response.json();
        console.log('联系求购者响应:', data);
        
        // 根据后端返回的错误码来判断
        if (!data) {
            ElMessage.error('网络异常，请稍后重试');
            return;
        }
        
        // 只有当code为200时才视为成功
        if (data.code !== 200) {
            // 根据不同错误码显示不同错误信息
            switch (data.code) {
                case 400:
                    ElMessage.error(data.message || '请求参数错误');
                    break;
                case 401:
                    ElMessage.error('用户未登录或登录已过期');
                    break;
                case 403:
                    ElMessage.error('您没有权限联系该求购者');
                    break;
                case 404:
                    ElMessage.error('求购信息不存在');
                    break;
                case 409:
                    ElMessage.error(data.message || '不能联系自己');
                    break;
                case 500:
                    ElMessage.error('服务器内部错误，请稍后重试');
                    break;
                default:
                    // 始终优先使用后端返回的错误信息
                    ElMessage.error(data.message || `联系失败(${data.code})`);
            }
            // 无论什么错误都不跳转
            return;
        }
        
        // 联系成功，显示成功消息
        ElMessage.success(data.message || '已成功发起联系');
        
        // 从后端响应中获取会话相关信息
        const responseData = data.data || {};
        
        // 跳转到聊天页面，使用后端返回的会话ID或对话相关信息
        if (responseData.conversationId || responseData.chatId) {
            router.push({
                path: '/chat',
                query: {
                    conversationId: responseData.conversationId || responseData.chatId,
                    // 后端可能还会返回其他有用的参数，也一并传递
                    sellerId: responseData.sellerId || request.user.id,
                    requestId: request.id
                }
            });
        } else {
            // 如果后端没有返回会话ID，则使用用户ID跳转
            router.push({
                path: '/chat',
                query: {
                    partnerId: request.user.id,
                    requestId: request.id
                }
            });
        }
    } catch (error) {
        console.error('联系用户失败:', error);
        ElMessage.error('联系用户失败，请稍后重试');
    }
};

// 分享求购信息
const shareRequest = (request) => {
    try {
        // 这里可以实现分享功能
        const shareUrl = `${window.location.origin}/requests/${request.id}`;
        // 复制链接到剪贴板
        navigator.clipboard.writeText(shareUrl)
            .then(() => {
    ElMessage.success('分享链接已复制到剪贴板');
            })
            .catch(err => {
                console.error('复制链接失败:', err);
                ElMessage.error('复制链接失败');
            });
    } catch (error) {
        console.error('分享失败:', error);
        ElMessage.error('分享失败，请稍后重试');
    }
};

// 添加收藏或取消收藏
const toggleFavorite = async (request) => {
    try {
        // 请求ID不存在时不进行操作
        if (!request.id) {
            ElMessage.error('求购信息不完整，无法收藏');
            return;
        }

        // 检查用户是否已登录
        const userInfo = localStorage.getItem('userInfo');
        const token = localStorage.getItem('token');
        if (!userInfo || !token) {
            ElMessage.warning('请先登录后再收藏求购信息');
            router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
            return;
        }

        // 判断当前是否已收藏
        const isFavorited = request.isFavorite;
        
        // 根据当前状态决定是收藏还是取消收藏
        let response;
        if (isFavorited) {
            // 取消收藏
            response = await unfavoriteRequest(request.id);
        } else {
            // 添加收藏
            response = await favoriteRequest(request.id);
        }

        // 检查响应是否成功
        if (response && response.code === 200) {
            // 更新求购信息的收藏状态
            request.isFavorite = !isFavorited;
            
            // 提示用户操作结果
            ElMessage.success(isFavorited ? '已取消收藏' : '收藏成功');
        } else {
            ElMessage.error(response?.message || '操作失败，请稍后重试');
        }
    } catch (error) {
        console.error('收藏操作出错:', error);
        ElMessage.error('操作失败，请稍后重试');
    }
};

// 切换分类选择
const toggleCategoryFilter = (categoryName) => {
    const index = categoryFilter.value.indexOf(categoryName);
    if (index === -1) {
        categoryFilter.value.push(categoryName);
    } else {
        categoryFilter.value.splice(index, 1);
    }
};

// 查找所有数组路径，用于调试
const findAllArrayPaths = (obj, currentPath = '', paths = []) => {
    if (!obj || typeof obj !== 'object') return paths;
    
    if (Array.isArray(obj)) {
        paths.push(currentPath || 'root');
    }
    
    for (const key in obj) {
        if (typeof obj[key] === 'object' && obj[key] !== null) {
            findAllArrayPaths(obj[key], currentPath ? `${currentPath}.${key}` : key, paths);
        }
    }
    
    return paths;
};

onMounted(() => {
    fetchCategories(); // 先获取分类
    fetchWantedData(); // 再获取求购数据
    
    // 添加滚动事件监听
    const mainContent = document.querySelector('.ios-main-content');
    if (mainContent) {
        mainContent.addEventListener('scroll', handleScroll);
    }
});

// 添加学校筛选方法
const handleSchoolSelect = (command) => {
    schoolFilter.value = command;
};

// 添加状态筛选相关数据
const statusFilter = ref('');

// 添加状态筛选方法
const handleStatusSelect = (command) => {
    statusFilter.value = command;
};
</script>

<style scoped>
/* 苹果风格基础样式 */
.ios-requests-page {
    font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'Helvetica Neue', Arial, sans-serif;
    background-color: #F5F5F7;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
    padding: 0;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
}

/* 分类网格样式 */
.category-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 12px;
    margin-top: 10px;
}

.category-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    padding: 10px 0;
    border-radius: 12px;
    transition: all 0.3s;
    background-color: #f5f7fa;
}

.category-item:hover {
    background-color: #eaedf1;
    transform: translateY(-2px);
}

.category-item.active {
    background-color: rgba(0, 122, 255, 0.1);
    color: #007AFF;
}

.category-icon-wrapper {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.category-icon {
    width: 28px;
    height: 28px;
    object-fit: contain;
}

.category-icon-component {
    font-size: 28px;
    color: #007AFF;
}

.category-name {
    font-size: 13px;
    text-align: center;
    margin-top: 5px;
    font-weight: 500;
    color: #333;
}

.category-item.active .category-icon-wrapper {
    background-color: #007AFF;
}

.category-item.active .category-icon-component {
    color: white;
}

.ios-container {
    max-width: 100%;
    margin: 0;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.ios-row {
    display: flex;
    flex: 1;
}

/* 左侧苹果风格筛选栏 */
.ios-sidebar {
    width: 280px;
    background-color: rgba(250, 250, 252, 0.7);
    backdrop-filter: blur(30px);
    -webkit-backdrop-filter: blur(30px);
    border-right: 1px solid rgba(209, 209, 214, 0.5);
    height: calc(100vh - 64px);
    overflow-y: auto;
    padding: 20px;
}

.ios-panel {
    background-color: rgba(255, 255, 255, 0.7);
    border-radius: 20px;
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
    overflow: hidden;
    border: 1px solid rgba(209, 209, 214, 0.5);
}

.panel-header {
    margin-bottom: 0;
    padding: 16px 20px;
    border-bottom: 1px solid rgba(209, 209, 214, 0.5);
    background-color: rgba(242, 242, 247, 0.8);
}

.panel-header h3 {
    font-size: 17px;
    font-weight: 600;
    margin: 0;
    color: #1C1C1E;
}

.ios-filter-list {
    display: flex;
    flex-direction: column;
    gap: 0;
    padding: 0;
}

.filter-section {
    padding: 18px 22px;
    border-bottom: 1px solid rgba(209, 209, 214, 0.5);
    position: relative;
}

.filter-section::after {
    content: '';
    position: absolute;
    left: 22px;
    right: 22px;
    bottom: 0;
    height: 1px;
    background: linear-gradient(to right, rgba(209, 209, 214, 0), rgba(209, 209, 214, 0.5) 50%, rgba(209, 209, 214, 0));
}

.filter-section:last-child::after {
    display: none;
}

.filter-section h4 {
    font-size: 15px;
    font-weight: 600;
    margin: 0 0 16px;
    color: #1C1C1E;
}

.type-options {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
}

.filter-buttons {
    display: flex;
    justify-content: flex-end;
    margin: 0;
    gap: 12px;
    padding: 16px 20px;
    background-color: rgba(242, 242, 247, 0.8);
}

:deep(.el-button) {
    border-radius: 12px;
    font-weight: 500;
    font-size: 14px;
    height: 38px;
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    letter-spacing: -0.01em;
}

:deep(.el-button--primary) {
    background: linear-gradient(135deg, #0A84FF 0%, #0066FF 100%);
    border: none;
    box-shadow: 0 2px 8px rgba(0, 122, 255, 0.25);
}

:deep(.el-button--primary:hover) {
    background: linear-gradient(135deg, #0091FF 0%, #0074FF 100%);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 122, 255, 0.4);
}

:deep(.el-button--default) {
    border: 1px solid rgba(0, 0, 0, 0.08);
    color: #3A3A3C;
    background-color: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
}

:deep(.el-button--default:hover) {
    background-color: rgba(255, 255, 255, 0.95);
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

:deep(.el-checkbox-group) {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px 10px;
}

:deep(.el-checkbox) {
    margin-right: 0;
    height: 30px;
    margin-left: 0;
}

:deep(.el-checkbox__inner) {
    border-radius: 6px;
    border-color: rgba(60, 60, 67, 0.3);
    width: 20px;
    height: 20px;
    transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
}

:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
    background-color: #007AFF;
    border-color: #007AFF;
    box-shadow: 0 1px 3px rgba(0, 122, 255, 0.3);
}

:deep(.el-checkbox__label) {
    font-size: 14px;
    color: #3A3A3C;
    line-height: 1.4;
}

:deep(.el-select .el-input__inner) {
    border-radius: 12px;
    border-color: rgba(209, 209, 214, 0.6);
    height: 40px;
    background-color: rgba(242, 242, 247, 0.6);
    transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
    padding: 0 15px;
}

:deep(.el-select .el-input__inner:hover),
:deep(.el-select .el-input__inner:focus) {
    border-color: #007AFF;
    background-color: rgba(255, 255, 255, 0.8);
    box-shadow: 0 0 0 3px rgba(0, 122, 255, 0.15);
}

.full-width {
    width: 100%;
}

/* 主内容区样式 */
.ios-main-content {
    flex: 1;
    padding: 0;
    background-color: #F5F5F7;
    overflow-y: auto;
    height: calc(100vh - 64px);
}

/* 合并标题和操作按钮到一行 */
.ios-content-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    background-color: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.ios-content-header h2 {
    font-size: 20px;
    font-weight: 600;
    margin: 0;
    color: #1C1C1E;
}

.header-actions {
    display: flex;
    align-items: center;
    gap: 16px;
}

.result-count {
    color: #8E8E93;
    font-size: 14px;
    font-weight: 500;
}

.ios-dropdown-trigger {
    display: flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    color: #3A3A3C;
    padding: 9px 14px;
    border-radius: 10px;
    background-color: rgba(142, 142, 147, 0.12);
    transition: background-color 0.2s;
    font-size: 14px;
    font-weight: 500;
}

.ios-dropdown-trigger:hover {
    background-color: rgba(142, 142, 147, 0.18);
}

.publish-button {
    display: flex;
    align-items: center;
    gap: 6px;
    background-color: #1890ff;
    border-color: #1890ff;
    border-radius: 8px;
    font-weight: 500;
    font-size: 14px;
    padding: 8px 16px;
    transition: all 0.3s;
    height: auto;
}

.publish-button:hover {
    background-color: #40a9ff;
    border-color: #40a9ff;
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

/* 求购卡片网格 */
.ios-requests-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
    gap: 20px;
    padding: 20px;
    background-color: #F5F5F7;
}

.ios-request-card {
    background-color: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
    border-radius: 16px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.06);
    overflow: hidden;
    transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1);
    border: 1px solid rgba(0, 0, 0, 0.04);
    display: flex;
    flex-direction: column;
}

.ios-request-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

.request-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

.user-info {
    display: flex;
    align-items: center;
    gap: 12px;
}

.user-info :deep(.el-avatar) {
    border: 2px solid #FFFFFF;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-details {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.user-name {
    font-weight: 600;
    font-size: 15px;
    color: #1C1C1E;
}

.user-school {
    font-size: 13px;
    color: #8E8E93;
}

.request-time {
    font-size: 13px;
    color: #8E8E93;
    font-weight: 500;
}

.request-body {
    padding: 20px;
    flex: 1;
}

.request-title {
    font-size: 17px;
    font-weight: 600;
    margin: 0 0 12px;
    color: #1C1C1E;
}

.request-content {
    font-size: 14px;
    color: #3A3A3C;
    margin-bottom: 20px;
    line-height: 1.5;
    height: 63px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}

.request-tags {
    display: flex;
    gap: 8px;
    margin-bottom: 16px;
}

.request-tags :deep(.el-tag) {
    border-radius: 10px;
    padding: 0 12px;
    height: 28px;
    line-height: 28px;
    font-size: 13px;
    font-weight: 500;
}

.request-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-top: 1px solid rgba(0, 0, 0, 0.05);
    background-color: rgba(242, 242, 247, 0.8);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
}

.request-budget {
    font-size: 16px;
    font-weight: 600;
    color: #FF3B30;
}

.request-actions {
    display: flex;
    gap: 10px;
}

.request-actions :deep(.el-button) {
    border-radius: 10px;
    font-weight: 500;
    font-size: 13px;
    box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

.request-actions :deep(.el-button--primary) {
    background-color: #007AFF;
    border-color: #007AFF;
}

.request-actions :deep(.el-button--primary:hover) {
    background-color: #0062CC;
    border-color: #0062CC;
}

.empty-result {
    padding: 30px;
    text-align: center;
}

/* 加载更多相关样式 */
.loading-more-container {
    padding: 20px;
    text-align: center;
}

.loading-indicator {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
    gap: 4px;
}

.loading-dot {
    width: 8px;
    height: 8px;
    background-color: #007AFF;
    border-radius: 50%;
    display: inline-block;
    margin: 0 2px;
    opacity: 0.6;
    animation: loadingDot 1.4s infinite ease-in-out;
}

.loading-dot:nth-child(1) {
    animation-delay: 0s;
}

.loading-dot:nth-child(2) {
    animation-delay: 0.2s;
}

.loading-dot:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes loadingDot {
    0%, 80%, 100% {
        transform: scale(0.6);
        opacity: 0.6;
    }
    40% {
        transform: scale(1);
        opacity: 1;
    }
}

.loading-text {
    margin-left: 8px;
    font-size: 14px;
    color: #8E8E93;
    font-weight: 500;
}

.all-loaded-text {
    color: #8E8E93;
    font-size: 14px;
    padding: 15px 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

.all-loaded-text span {
    position: relative;
    padding: 0 10px;
}

.load-more-hint {
    color: #8E8E93;
    font-size: 14px;
    padding: 15px 0;
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 初始加载状态样式 */
.initial-loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
    height: 300px;
}

.loading-spinner {
    width: 50px;
    height: 50px;
    margin-bottom: 20px;
    animation: spinnerRotate 2s linear infinite;
}

@keyframes spinnerRotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.spinner {
    animation: spinnerDash 1.5s ease-in-out infinite;
    stroke: #007AFF;
    stroke-linecap: round;
}

@keyframes spinnerDash {
    0% {
        stroke-dasharray: 1, 150;
        stroke-dashoffset: 0;
    }
    50% {
        stroke-dasharray: 90, 150;
        stroke-dashoffset: -35;
    }
    100% {
        stroke-dasharray: 90, 150;
        stroke-dashoffset: -124;
    }
}

.loading-text-container {
    text-align: center;
}

.loading-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 5px;
    color: #1C1C1E;
}

.loading-subtitle {
    font-size: 14px;
    color: #8E8E93;
    margin-top: 5px;
}

/* 空结果提示样式 */
.empty-hint {
    font-size: 14px;
    color: #8E8E93;
    margin-top: 8px;
}

/* 对话框样式 */
.ios-dialog {
    font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'Helvetica Neue', Arial, sans-serif;
}

.ios-dialog :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.25);
}

.ios-dialog :deep(.el-dialog__header) {
    padding: 16px 20px;
    margin: 0;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    background-color: rgba(242, 242, 247, 0.8);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
}

.ios-dialog :deep(.el-dialog__title) {
    font-size: 17px;
    font-weight: 600;
    color: #1C1C1E;
}

.ios-dialog :deep(.el-dialog__headerbtn) {
    top: 16px;
    right: 16px;
}

.ios-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #8E8E93;
}

.ios-dialog :deep(.el-dialog__body) {
    padding: 24px;
}

.ios-dialog :deep(.el-dialog__footer) {
    padding: 16px 20px;
    border-top: 1px solid rgba(0, 0, 0, 0.05);
    background-color: rgba(242, 242, 247, 0.8);
    backdrop-filter: blur(20px);
    -webkit-backdrop-filter: blur(20px);
}

.ios-dialog :deep(.el-button) {
    font-weight: 500;
    border-radius: 10px;
    height: 38px;
}

.ios-dialog :deep(.el-button--primary) {
    background-color: #007AFF;
    border-color: #007AFF;
}

.ios-dialog :deep(.el-button--primary:hover) {
    background-color: #0062CC;
    border-color: #0062CC;
    box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
}

.ios-dialog :deep(.el-form-item__label) {
    font-weight: 500;
    color: #3A3A3C;
    font-size: 15px;
    padding-bottom: 8px;
}

.ios-dialog :deep(.el-input__inner),
.ios-dialog :deep(.el-textarea__inner) {
    border-radius: 10px;
    border-color: rgba(142, 142, 147, 0.2);
}

.ios-dialog :deep(.el-radio__label) {
    color: #3A3A3C;
    font-size: 14px;
}

.ios-dialog :deep(.el-radio__input.is-checked .el-radio__inner) {
    background-color: #007AFF;
    border-color: #007AFF;
}

.ios-dialog :deep(.el-radio__input.is-checked + .el-radio__label) {
    color: #007AFF;
}

.ios-dialog :deep(.el-select) {
    width: 100%;
}

/* 响应式调整 */
@media (max-width: 992px) {
    .ios-row {
        flex-direction: column;
    }
    
    .ios-sidebar {
        width: 100%;
        border-right: none;
        border-bottom: 1px solid #f0f0f0;
    }
    
    .ios-search-bar {
        flex-direction: column;
        align-items: flex-start;
        gap: 15px;
    }
    
    .search-input-wrapper {
        width: 100%;
    }
    
    .filter-actions {
        width: 100%;
        justify-content: space-between;
    }
}

@media (max-width: 768px) {
    .ios-requests-grid {
        grid-template-columns: 1fr;
    }
}

/* 价格区间显示样式 */
.budget-range-display {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 12px;
    gap: 10px;
}

.price-label {
    font-size: 16px;
    font-weight: 600;
    color: #007AFF;
    background-color: rgba(0, 122, 255, 0.1);
    border-radius: 10px;
    padding: 6px 10px;
    min-width: 80px;
    text-align: center;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.price-separator {
    font-size: 15px;
    color: #8E8E93;
}

.price-range-text {
    margin-top: 12px;
    font-size: 13px;
    color: #8E8E93;
    text-align: center;
}

/* 调试相关样式 */
.debug-content {
    max-height: 400px;
    overflow-y: auto;
    font-family: monospace;
}

.debug-item {
    margin-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
    padding-bottom: 8px;
}

.debug-item .label {
    font-weight: bold;
    display: block;
    margin-bottom: 4px;
    color: #333;
}

.debug-item .value {
    display: block;
    word-break: break-all;
    white-space: pre-wrap;
    background: #f9f9f9;
    padding: 4px;
    border-radius: 4px;
    color: #0066cc;
}

.debug-tools {
    margin-top: 20px;
    text-align: center;
}

/* 收藏按钮样式 */
.request-actions-top {
    display: flex;
    align-items: center;
    gap: 10px;
}

.favorite-button {
    width: 32px;
    height: 32px;
    padding: 0;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: all 0.2s;
    background-color: rgba(242, 242, 247, 0.8);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(0, 0, 0, 0.04);
    color: #8E8E93;
    margin-left: 8px;
}

.favorite-button.is-favorite {
    color: #FF9500;
    background-color: rgba(255, 149, 0, 0.1);
    border-color: rgba(255, 149, 0, 0.2);
}

.favorite-button:hover {
    transform: scale(1.1);
    background-color: rgba(255, 255, 255, 0.95);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.favorite-button.is-favorite:hover {
    background-color: rgba(255, 149, 0, 0.2);
}

/* 添加分类图标样式 */
.category-checkbox-content {
    display: flex;
    align-items: center;
    gap: 6px;
}

.category-icon-img, .tag-icon-img {
    width: 18px;
    height: 18px;
    object-fit: contain;
}

.category-icon-component, .tag-icon-component {
    font-size: 18px;
    color: #8E8E93;
}

.tag-with-icon {
    display: flex;
    align-items: center;
    gap: 4px;
}

/* 添加选择框内的图标样式 */
.category-option {
    display: flex;
    align-items: center;
    gap: 8px;
}

/* Apple风格弹窗样式 */
.apple-style-dialog :deep(.el-dialog) {
    border-radius: 16px;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
    backdrop-filter: blur(10px);
    overflow: hidden;
}

.apple-style-dialog :deep(.el-dialog__header) {
    padding: 20px 24px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.05);
    background: rgba(248, 248, 248, 0.8);
    backdrop-filter: blur(10px);
    text-align: center;
}

.apple-style-dialog :deep(.el-dialog__title) {
    font-size: 18px;
    font-weight: 600;
    color: #333;
}

.apple-style-dialog :deep(.el-dialog__body) {
    padding: 24px;
}

.apple-style-dialog :deep(.el-form-item) {
    margin-bottom: 20px;
}

.apple-style-dialog :deep(.el-form-item__label) {
    color: #333;
    font-weight: 500;
}

.apple-style-input {
    transition: all 0.3s;
}

.apple-style-input :deep(.el-input__wrapper) {
    border-radius: 10px;
    border: 1px solid #dcdfe6;
    box-shadow: none;
    transition: all 0.3s;
}

.apple-style-input :deep(.el-input__wrapper:hover),
.apple-style-input :deep(.el-input__wrapper:focus-within) {
    border-color: #409eff;
    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.apple-style-textarea {
    transition: all 0.3s;
}

.apple-style-textarea :deep(.el-textarea__inner) {
    border-radius: 10px;
    border: 1px solid #dcdfe6;
    box-shadow: none;
    transition: all 0.3s;
}

.apple-style-textarea :deep(.el-textarea__inner:hover),
.apple-style-textarea :deep(.el-textarea__inner:focus) {
    border-color: #409eff;
    box-shadow: 0 0 0 3px rgba(64, 158, 255, 0.1);
}

.apple-style-select {
    border-radius: 10px;
}

.apple-style-input-number {
    border-radius: 10px;
}

.apple-style-dialog :deep(.el-dialog__footer) {
    padding: 16px 24px;
    border-top: 1px solid rgba(0, 0, 0, 0.05);
    background: rgba(248, 248, 248, 0.8);
    backdrop-filter: blur(10px);
}

.apple-style-btn {
    border-radius: 10px;
    font-weight: 500;
    padding: 10px 20px;
    transition: all 0.3s;
}

.apple-style-btn.confirm-btn {
    background: linear-gradient(135deg, #42a6ff, #0077ff);
    border: none;
    box-shadow: 0 2px 6px rgba(0, 102, 255, 0.2);
}

.apple-style-btn.cancel-btn {
    background: rgba(142, 142, 147, 0.12);
    color: #333;
    border: none;
}

.apple-style-btn.confirm-btn:hover {
    background: linear-gradient(135deg, #3a95e9, #0066dd);
    transform: translateY(-1px);
    box-shadow: 0 4px 10px rgba(0, 102, 255, 0.3);
}

.apple-style-btn.cancel-btn:hover {
    background: rgba(142, 142, 147, 0.18);
    transform: translateY(-1px);
}

.form-item-tips {
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
    margin-top: 4px;
}

.location-input-container {
    position: relative;
}

.location-status {
    margin-top: 8px;
}

.modern-input {
    font-size: 14px;
}

.school-select-wrapper {
    margin-right: 16px;
}

.school-select-button {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    background-color: #f0f4ff;
    padding: 8px 16px;
    border-radius: 8px;
    transition: all 0.3s;
}

.school-select-button:hover {
    background-color: #e0e7ff;
}

.school-select-button span {
    margin-right: 4px;
}

/* 修改已有样式，确保元素间距正确 */
.header-actions {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.filter-button-wrapper {
    margin-right: 16px;
}

.filter-button {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    background-color: #f0f4ff;
    padding: 8px 16px;
    border-radius: 8px;
    transition: all 0.3s;
}

.filter-button:hover {
    background-color: #e0e7ff;
}

.filter-button span {
    margin-right: 4px;
}

.school-select-button {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    background-color: #f0f4ff;
    padding: 8px 16px;
    border-radius: 8px;
    transition: all 0.3s;
}

.school-select-button:hover {
    background-color: #e0e7ff;
}

.school-select-button span {
    margin-right: 4px;
}

/* 修改发布按钮样式，使其与学校选择按钮相似 */
.publish-button {
    display: flex;
    align-items: center;
    gap: 6px;
    background-color: #1890ff;
    border-color: #1890ff;
    border-radius: 8px;
    font-weight: 500;
    font-size: 14px;
    padding: 8px 16px;
    transition: all 0.3s;
    height: auto;
}

.publish-button:hover {
    background-color: #40a9ff;
    border-color: #40a9ff;
    transform: translateY(-2px);
    box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.status-select-wrapper {
    margin-right: 16px;
}

.status-select-button {
    display: flex;
    align-items: center;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    background-color: #f0f4ff;
    padding: 8px 16px;
    border-radius: 8px;
    transition: all 0.3s;
}

.status-select-button:hover {
    background-color: #e0e7ff;
}

.status-select-button span {
    margin-right: 4px;
}
</style> 